package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.util.StringUtils;

import io.finer.erp.jeecg.bas.entity.ZrkQuestion;
import io.finer.erp.jeecg.bas.entity.ZrkTs;
import io.finer.erp.jeecg.bas.entity.ZrkTsources;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.service.IZrkTsService;
import io.finer.erp.jeecg.bas.service.IZrkTsourcesService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 客户投诉记录
 * @Author: jeecg-boot
 * @Date:   2020-08-20
 * @Version: V1.0
 */
@Api(tags="客户投诉记录")
@RestController
@RequestMapping("/bas/zrkTs")
@Slf4j
public class ZrkTsController extends JeecgController<ZrkTs, IZrkTsService> {

	@Autowired
	private IZrkTsService zrkTsService;

	@Autowired
	private IZrkTsourcesService zrkTsourcesService;

	@Autowired
	private IStkIoBillService stkIoBillService;

	@Autowired
	private IZzShoporderService zzShoporderService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param zrkTs
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "客户投诉记录-分页列表查询")
	@ApiOperation(value="客户投诉记录-分页列表查询", notes="客户投诉记录-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkTs zrkTs,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<ZrkTs> queryWrapper = QueryGenerator.initQueryWrapper(zrkTs, req.getParameterMap());
		Page<ZrkTs> page = new Page<ZrkTs>(pageNo, pageSize);
		IPage<ZrkTs> pageList = zrkTsService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 * @param zrkTs
	 * @return
	 */
	@AutoLog(value = "客户投诉记录-添加")
	@ApiOperation(value="客户投诉记录-添加", notes="客户投诉记录-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkTs zrkTs) {
		zrkTsService.save(zrkTs);
		//主表添加成功时,自动添加子表记录(完成从商城订单到投诉到原材料、车间任务、班组的追溯)
		ZrkTsources zrkTsource=new ZrkTsources();
		zrkTsource.setTsId(zrkTs.getId());
		zrkTsource.setTsProductid(zrkTs.getCusProduct());
		zrkTsource.setMallId(zrkTs.getCusOrder());
		//查询销售出库单 source_type:stk_io_bill..201
		Map<String,Object> columnMap=new HashMap<String,Object>();
		columnMap.put("source_type", "stk_io_bill..201");
		columnMap.put("source_no", zrkTs.getCusOrder());//查询原单号为销售单号的销售出库单
		Collection<StkIoBill> stkIoBillList=stkIoBillService.listByMap(columnMap);
		int i=0;
		//关联销售出库单
		if(null!=stkIoBillList&&stkIoBillList.size()>0) {
			Iterator<StkIoBill> iterator=stkIoBillList.iterator();
			while(iterator.hasNext()) {
				if(i==0) {
					StkIoBill sib=iterator.next();
					i+=1;
					zrkTsource.setStkIoBillNo(sib.getBillNo());
				}else {
					break;
				}
			}
		}
		//关联车间任务单,根据商城订单号查询车间任务单
		Map<String,Object> shopMap=new HashMap<String,Object>();
		shopMap.put("order_no", zrkTs.getCusOrder());
		Collection<ZzShoporder> shoporderList=zzShoporderService.listByMap(shopMap);
		int j=0;
		if(null!=null&&shoporderList.size()>0) {
			Iterator<ZzShoporder> iterator=shoporderList.iterator();
			while(iterator.hasNext()) {
				if(j==0) {
					ZzShoporder shoporder=iterator.next();
					zrkTsource.setTsProduceid(shoporder.getId());
				}else {
					break;
				}
			}
		}
		zrkTsourcesService.save(zrkTsource);//数据持久化操作
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 * @param zrkTs
	 * @return
	 */
	@AutoLog(value = "客户投诉记录-编辑")
	@ApiOperation(value="客户投诉记录-编辑", notes="客户投诉记录-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkTs zrkTs) {
		//根据id查询该条信息
		ZrkTs zt=zrkTsService.getById(zrkTs.getId());
		//当审核状态为通过时，锁定该条数据，不允许再次审核
		if(zt.getIsLock()!=1) {
			String isCheck="";
			try {
				isCheck=zrkTs.getIsCheck();
			}catch(Exception e) {
				isCheck="";
			}
			//由于编辑、审核合二为一，此处需要判断is_check是否有值从而确定是否为审核
			if(StringUtils.areNotEmpty(isCheck)) {
				//获取登录用户信息
				LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
				zrkTs.setCheckUser(sysUser.getId());//设置审核人
				zrkTs.setIsLock(1);//锁定该条数据，不允许再次审核
			}
			zrkTsService.updateById(zrkTs);
			return Result.ok("编辑成功!");
		}else {
			//      			zrkQuestion.setIsCheck(zq.getIsCheck());//保持原来的状态不变
			return Result.ok("数据已锁定!");
		}
	}
	
	/**
	 * 通过id查询投诉单数据
	 * @param id
	 * @return
	 */
	@AutoLog(value = "通过id查询投诉单数据")
	@ApiOperation(value="通过id查询投诉单数据", notes="通过id查询投诉单数据")
	@DeleteMapping(value = "/queryTSData")
	public Result<?> queryTSData(@RequestParam(name="id",required=true) String id) {
		return Result.ok(zrkTsService.getById(id));
	}


	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户投诉记录-通过id删除")
	@ApiOperation(value="客户投诉记录-通过id删除", notes="客户投诉记录-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkTsService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "客户投诉记录-批量删除")
	@ApiOperation(value="客户投诉记录-批量删除", notes="客户投诉记录-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkTsService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, ZrkTs zrkTs) {
		return super.exportXls(request, zrkTs, ZrkTs.class, "客户投诉记录");
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, ZrkTs.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-客户投诉追溯记录-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "客户投诉追溯记录-通过主表ID查询")
	@ApiOperation(value="客户投诉追溯记录-通过主表ID查询", notes="客户投诉追溯记录-通过主表ID查询")
	@GetMapping(value = "/listZrkTsourcesByMainId")
	public Result<?> listZrkTsourcesByMainId(ZrkTsources zrkTsources,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<ZrkTsources> queryWrapper = QueryGenerator.initQueryWrapper(zrkTsources, req.getParameterMap());
		Page<ZrkTsources> page = new Page<ZrkTsources>(pageNo, pageSize);
		IPage<ZrkTsources> pageList = zrkTsourcesService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 * 添加
	 * @param zrkTsources
	 * @return
	 */
	@AutoLog(value = "客户投诉追溯记录-添加")
	@ApiOperation(value="客户投诉追溯记录-添加", notes="客户投诉追溯记录-添加")
	@PostMapping(value = "/addZrkTsources")
	public Result<?> addZrkTsources(@RequestBody ZrkTsources zrkTsources) {
		zrkTsourcesService.save(zrkTsources);
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 * @param zrkTsources
	 * @return
	 */
	@AutoLog(value = "客户投诉追溯记录-编辑")
	@ApiOperation(value="客户投诉追溯记录-编辑", notes="客户投诉追溯记录-编辑")
	@PutMapping(value = "/editZrkTsources")
	public Result<?> editZrkTsources(@RequestBody ZrkTsources zrkTsources) {
		zrkTsourcesService.updateById(zrkTsources);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户投诉追溯记录-通过id删除")
	@ApiOperation(value="客户投诉追溯记录-通过id删除", notes="客户投诉追溯记录-通过id删除")
	@DeleteMapping(value = "/deleteZrkTsources")
	public Result<?> deleteZrkTsources(@RequestParam(name="id",required=true) String id) {
		zrkTsourcesService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "客户投诉追溯记录-批量删除")
	@ApiOperation(value="客户投诉追溯记录-批量删除", notes="客户投诉追溯记录-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkTsources")
	public Result<?> deleteBatchZrkTsources(@RequestParam(name="ids",required=true) String ids) {
		this.zrkTsourcesService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportZrkTsources")
	public ModelAndView exportZrkTsources(HttpServletRequest request, ZrkTsources zrkTsources) {
		// Step.1 组装查询条件
		QueryWrapper<ZrkTsources> queryWrapper = QueryGenerator.initQueryWrapper(zrkTsources, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ZrkTsources> pageList = zrkTsourcesService.list(queryWrapper);
		List<ZrkTsources> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "客户投诉追溯记录"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ZrkTsources.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("客户投诉追溯记录报表", "导出人:" + sysUser.getRealname(), "客户投诉追溯记录"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importZrkTsources/{mainId}")
	public Result<?> importZrkTsources(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkTsources> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkTsources.class, params);
				for (ZrkTsources temp : list) {
					temp.setTsId(mainId);
				}
				long start = System.currentTimeMillis();
				zrkTsourcesService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-客户投诉追溯记录-end----------------------------------------------*/




}
